package com.mrs.controller;

import com.mrs.common.ResponseResult;
import com.mrs.common.enums.AppHttpCodeEnum;
import com.mrs.common.vo.AdminUserInfoVo;
import com.mrs.common.vo.RoutesVo;
import com.mrs.common.vo.UserInfoVo;
import com.mrs.entity.LoginUser;


import com.mrs.entity.Menu;
import com.mrs.entity.User;
import com.mrs.exception.SystemException;
import com.mrs.service.LoginService;
import com.mrs.service.MenuService;
import com.mrs.service.RoleService;
import com.mrs.utils.BeanCopyUtils;
import com.mrs.utils.RedisCache;
import com.mrs.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * description: BlogLoginController
 * date: 2022/8/7 22:01
 * author: MR.孙
 */
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){

        if(!StringUtils.hasText(user.getUserName())){
            //提示必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }

        return loginService.login(user);
    }


    @GetMapping("/getInfo")
    public  ResponseResult<AdminUserInfoVo> getInfo(){
        //查询当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        //根据用户id查询当前权限列表
        List<String>  permissions =menuService
                .selectPermissionByUserId(loginUser.getUser().getId());


        //根据用户id查询当前用户拥有的角色
        List<String> roles=roleService.selectRolesByUserId(loginUser.getUser().getId());


        //获取用户信息
        User user = loginUser.getUser();
        //获取UserInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        //封装对象返回

        //封装AdminUserInfoVo
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(permissions, roles, userInfoVo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    //不同用户显示不同的路由菜单
    @GetMapping("/getRouters")
    public ResponseResult<RoutesVo> getRouters(){
        Long userId = SecurityUtils.getUserId();

        //查询menu 结果是tree形式
        List<Menu> menus=menuService.selectMenuRoutesTreeByUserId(userId);

        //封装结果返回
        return ResponseResult.okResult(new RoutesVo(menus));
    }


    //退出登录
    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

}
